<?php
/**
 +------------------------------------------------------------------------------
 * mysqli类 驱动
 +------------------------------------------------------------------------------
 * @version 3.0
 * @author  WangXian
 * @package ephp
 * @creation date 2010-8-12
 * @Modified date 2010-12-21 23:16:58
 +------------------------------------------------------------------------------
 */
class db
{
	public $sql='';
	private $_conn = false;
	function __construct($db_config='default')
	{
		#获取当前数据库配制
		if(false == ( $iconfig = C($db_config, 'db') ) )
		{
			throw new ephpException('数据库配制db.config.php中'.$db_config.'没有配置。', 2001);
		}
		//dump($iconfig);
		//wlog('db-conn.log',date('H:i:s').':connecting....');
		$this->_conn = new mysqli($iconfig['host'], $iconfig['user'], $iconfig['password'], $iconfig['dbname']);
		if(mysqli_connect_errno())
		{
			throw new ephpException('Can not connect to your database.'. mysqli_connect_error(), 2002);
		}
		$this->_conn->set_charset("utf8");
	}

	/**
	 * MYSQL query
	 * @param  String $sql
	 * @return mixed
	 */
	function query($sql)
	{
		$this->sql = $sql;

		#是否记录 SQL log
		if( true == C('sql_log') )
			wlog('SQL-Log-'.date('Y-m-d').'.log', '['. date('H:i:s') .']'.$sql);

		if(true == ( $rs = $this->_conn->query($sql) ) )
		{
			#统计数据库查询次数
			global $run_dbquery_count;
			$run_dbquery_count++; #数据库查询次数

			return $rs;
		}
		else if( C('exception_print')) throw new ephpException('执行mysqli::query()出现错误：'.$this->_conn->error.'<br />SQL：'.$sql, 11251156);
		else return false;
	}
	
	/**
	 * 获取单条记录,返回数据格式array
	 * @param string $sql
	 * @return mixed
	 */
	function fetch_array($sql)
	{
		$this->sql = $sql;
		return $this->query($sql)->fetch_assoc();
	}
	
	/**
	 * 获取多条记录，返回数据格式array
	 * @param string $sql
	 * @return mixed
	 */
	function fetch_arrays($sql)
	{
		$this->sql = $sql;
		$rs = $this->query($sql);
		$data = null;
		while(true == ($row = $rs->fetch_assoc()))
		{
			$data[] = $row;
		}
		$rs->free();
		return $data;
	}
	
	/**
	 * 获取一条记录,以object的方式返回数据
	 * @param string $sql
	 */
	function fetch_object($sql)
	{
		$this->sql = $sql;
		return $this->query($sql)->fetch_object();
	}
	
	/**
	 * 查询多条记录，以objects的方式返回数据
	 * @param string $sql
	 */
	function fetch_objects($sql)
	{
		$this->sql = $sql;
		$rs = $this->query($sql);
		$data = null;
		while(true == ($row = $rs->fetch_object()) )
		{
			$data[] = $row;
		}
		$rs->free();
		return $data;
	}

	/** return last insert id。 **/
	public function insert_id()
	{
		return $this->_conn->insert_id;
	}

	/** 影响的行数。 **/
	public function affected_rows()
	{
		return $this->_conn->affected_rows;
	}

	/** 最后执行的sql语句。 **/
	public function getLastSql()
	{
		return $this->sql;
	}
}
/* End of file mysqli.class.php */
/* Location: ./_framework/dbdrivers/mysqli.class.php */